#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/channel.h>

DEFINE_string(d, "world", "POST this data to the http server");
DEFINE_int32(timeout_ms, 2000, "RPC timeout in milliseconds");

// ./http_client 0.0.0.0:8000 -d "world"
// ./http_client 0.0.0.0:8000 -d "world" --http_verbose=true

int main(int argc, char* argv[]) {
    GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);

    if (argc != 2) {
        LOG(ERROR) << "Usage: ./http_client \"0.0.0.0:8000\"";
        return -1;
    }

    // 创建 Channel
    brpc::Channel channel;
    brpc::ChannelOptions options;
    options.protocol = "http";
    options.timeout_ms = FLAGS_timeout_ms;

    // 初始化 channel，使用空字符串作为 load_balancer
    if (channel.Init(argv[1], "", &options) != 0) {
        LOG(ERROR) << "Fail to initialize channel";
        return -1;
    }

    // 发送请求
    brpc::Controller cntl;
    cntl.http_request().uri() = "/HttpService/Echo";  // 指定运行方法
    cntl.http_request().set_method(brpc::HTTP_METHOD_POST);
    cntl.request_attachment().append(FLAGS_d);

    // 不使用 stub.Echo，改用 channel.CallMethod（HTTP方式）
    channel.CallMethod(NULL, &cntl, NULL, NULL, NULL);
    if (cntl.Failed()) {
        LOG(ERROR) << cntl.ErrorText();
        return -1;
    }

    // 打印响应
    std::cout << "Server response: " << cntl.response_attachment() << std::endl;
    return 0;
}
